import { Injectable } from '@nestjs/common';
import { CreateTetriDto } from './dto/create-tetri.dto';
import { UpdateTetriDto } from './dto/update-tetri.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Tetri } from './entities/tetri.entity';
import { UserEntity } from '../user/entities/user.entity';
import { Repository } from 'typeorm';

@Injectable()
export class TetrisService {
  constructor(
    @InjectRepository(Tetri)
    private readonly TetriRepository: Repository<Tetri>,
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
  ) {}

  async create(createTetriDto: Tetri) {
    console.log(createTetriDto);

    // 根据userId查询用户信息
    const user = await this.userRepository.findOne({
      where: { id: createTetriDto.userId },
    });
    if (!user) {
      throw new Error('用户不存在');
    }
    createTetriDto.user = user;

    return this.TetriRepository.save(createTetriDto);
  }

  async findTop10() {
    let data: Tetri[] = await this.TetriRepository.createQueryBuilder('tetris')
      .leftJoinAndSelect('tetris.user', 'user') // 加载关联的user信息
      .getMany();
    // 根据score排序，取前十条
    data.sort((a, b) => b.score - a.score);
    data = data.slice(0, 10);
    return data;
  }

  findOne(id: number) {
    return `This action returns a #${id} tetri`;
  }

  update(id: number, updateTetriDto: UpdateTetriDto) {
    return `This action updates a #${id} tetri`;
  }

  remove(id: number) {
    return `This action removes a #${id} tetri`;
  }
}
